<template>
	<view class="content">
		<view class="content-box" @touchstart="touchstart" id="content-box" :class="{'content-showfn':showFunBtn}">
			<!-- 背景图- 定位方式 -->
			<!-- <image class="content-box-bg" :src="_user_info.chatBgImg" :style="{ height: imgHeight }"></image> -->
			<view class="content-box-loading" v-if="!loading">
				<u-loading mode="flower"></u-loading>
			</view>
			<view class="message" v-for="(item, index) in messageList" :key="index" :id="`msg-${item.hasBeenSentId}`">
				<view class="message-item " :class="item.isItMe ? 'right' : 'left'">
					<image class="img" :src="item.fromUserHeadImg" mode="" @tap="linkToBusinessCard(item.fromUserId)"></image>
					<!-- contentType = 1 文本 -->
					<view class="content" v-if="item.contentType == 1">{{ item.content }}</view>
					<!-- contentType = 2 语音 -->
					<view class="content contentType2" :class="[{ 'content-type-right': item.isItMe }]" v-if="item.contentType == 2"
					 @tap="handleAudio(item)" hover-class="contentType2-hover-class" :style="{width:`${130+(item.contentDuration*2)}rpx`}">
						<view class="voice_icon" :class="[
								{ voice_icon_right: item.isItMe },
								{ voice_icon_left: !item.isItMe },
								{ voice_icon_right_an: item.anmitionPlay && item.isItMe },
								{ voice_icon_left_an: item.anmitionPlay && !item.isItMe }
							]"></view>
						<view class="">{{ item.contentDuration }}''</view>
					</view>
					<!-- contentType = 3 图片 -->
					<view class="content contentType3" v-if="item.contentType == 3" @tap="viewImg([item.content])">
						<image :src="item.content" class="img" mode="widthFix" @load="loadImage()"></image>
					</view>
					<!-- contentType = 4 位 -->
					<view class="content contentType3" v-if="item.contentType == 4" @tap="">
						<view class="" style="border: #09BB07 1rpx dashed;padding: 5rpx;border-radius: 10rpx;">
							<view class="" style="color: #0A98D5;">发送一个位置</view>
							<view class="uni-flex">
								<view class="" style="color: #09BB07;font-size: 28rpx;border-top: #576B95 1rpx solid;">
									{{item.info.address}}{{item.content}}
								</view>
								<view class="" style="padding:0 5rpx;margin-left: 5rpx;">
									<image src="../../static/image/ditu.png" mode="" style="width:120rpx;height:120rpx;"></image>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部聊天输入框 -->
		<view class="input-box" :class="{ 'input-box-mpInputMargin': mpInputMargin }">
			<view class="input-box-flex">
				<!-- #ifndef H5 -->
				<image v-if="chatType === 'voice'" class="icon_img" :src="require('@/static/voice.png')" @click="switchChatType('keyboard')"></image>
				<image v-if="chatType === 'keyboard'" class="icon_img" :src="require('@/static/keyboard.png')" @click="switchChatType('voice')"></image>
				<!-- #endif -->
				<view class="input-box-flex-grow">
					<input v-if="chatType === 'voice'" type="text" class="content" id="input" v-model="formData.content"
					 :hold-keyboard="true" confirm-type="go" :confirm-hold="true" placeholder-style="color:#DDDDDD;"
					 :cursor-spacing="10" @confirm="sendMsg(null)" :adjust-position="true"/>
					<view class="voice_title" v-if="chatType === 'keyboard'" :style="{ background: recording ? '#c7c6c6' : '#FFFFFF' }"
					 @touchstart.stop.prevent="startVoice" @touchmove.stop.prevent="moveVoice" @touchend.stop="endVoice"
					 @touchcancel.stop="cancelVoice">
						{{ voiceTitle }}
					</view>
				</view>
				<!-- <image src="../../static/biaoqing.png" mode="" style="height: 50rpx;width: 50rpx;position: relative;left: 15rpx;"></image> -->

				<!-- 功能性按钮 -->
				<image class=" icon_btn_add" :src="require('@/static/add.png')" @tap="switchFun"></image>

				<!-- #ifdef H5 -->
				<button class="btn" type="primary" size="mini" @touchend.prevent="sendMsg(null)">发送</button>
				<!-- #endif -->
			</view>

			<view class="fun-box" :class="{'show-fun-box':showFunBtn}">
				<u-grid :col="4" hover-class="contentType2-hover-class" :border="false" @click="clickGrid">
					<u-grid-item v-for="(item, index) in funList" :index="index" :key="index" bg-color="#eaeaea">
						<u-icon :name="item.icon" size="52"></u-icon>
						<view class="grid-text">{{ item.title }}</view>
					</u-grid-item>
				</u-grid>
			</view>

		</view>

		<!-- //语音动画 -->
		<view class="voice_an" v-if="recording">
			<view class="voice_an_icon">
				<view id="one" class="wave"></view>
				<view id="two" class="wave"></view>
				<view id="three" class="wave"></view>
				<view id="four" class="wave"></view>
				<view id="five" class="wave"></view>
				<view id="six" class="wave"></view>
				<view id="seven" class="wave"></view>
			</view>
			<view class="text">{{voiceIconText}}</view>
		</view>
	</view>
</template>

<script>
	var util = require('../../common/util.js');
	var formatLocation = util.formatLocation;
	import amap from '../../common/amap-wx.js';
	import permision from "@/js_sdk/wa-permission/permission.js"
	
	import {
		mapState
	} from "vuex";
	export default {
		data() {
			return {
				fromUserInfo: {},
				formData: {
					content: '',
					limit: 15,
					index: 1
				},
				messageList: [],
				nextReqMessageID: null, //加载更多的参数
				isCompleted: true,
				messageId: "",
				loading: true, //标识是否正在获取数据
				imgHeight: '1000px',
				mpInputMargin: false, //适配微信小程序 底部输入框高度被顶起的问题
				chatType: "voice", // 图标类型 'voice'语音 'keyboard'键盘
				voiceTitle: '按住 说话',
				Recorder: uni.getRecorderManager(),
				Audio: uni.createInnerAudioContext(),
				recording: false, //标识是否正在录音
				isStopVoice: false, //加锁 防止点击过快引起的当录音正在准备(还没有开始录音)的时候,却调用了stop方法但并不能阻止录音的1111
				voiceInterval: null,
				voiceTime: 0, //总共录音时长
				canSend: true, //是否可以发送
				// conversationActive:null,
				PointY: 0, //坐标位置
				voiceIconText: "正在录音...",
				showFunBtn: false, //是否展示功能型按钮
				AudioExam: null, //正在播放音频的实例
				meHaed: "",
				// toUserId:"",
				woUserInfo: uni.getStorageSync("userInfo"),
				funList: [{
						icon: "photo-fill",
						title: "照片",
						uploadType: ["album"]
					},
					{
						icon: "camera-fill",
						title: "拍摄",
						uploadType: ["camera"]
					},
					{
						icon: "map-fill",
						title: "位置",
						uploadType: ["camera"]
					},

				],
				amapPlugin: null,
				key: '25819d0ded50cb1384a7a0841b5d717e'
			};
		},
		computed: {
			...mapState({
				currentMessageList: state => state.currentMessageList,
				toUserId: state => state.toUserId,
			}),


		},
		watch: {
			currentMessageList(newVal, oldVal) {
				this.msgList = newVal
				console.log(newVal);
				console.log(oldVal);
				this.screenMsg(newVal, oldVal)
			},
		},
		methods: {
			
			async requestAndroidPermission(permisionID) {
				var result = await permision.requestAndroidPermission(permisionID)
				var strStatus
				if (result == 1) {
					strStatus = "已获得授权"
				} else if (result == 0) {
					strStatus = "未获得授权"
				} else {
					strStatus = "被永久拒绝权限"
				}
				// uni.showModal({
				// 	content: permisionID + strStatus,
				// 	showCancel: false
				// });
			},
			loadImage() {
				// 滚动到底部
				if (this.formData.index == 1) {
					this.$nextTick(function() {
						//进入页面滚动到底部
						uni.pageScrollTo({
							scrollTop: 9999,
							duration: 0
						});
					});
				}
			},
			// 接受消息(定位消息)
			screenMsg(newVal, oldVal) {
				var that = this;
				var userInfo = uni.getStorageSync("userInfo");
				var wodeTouxiang = that.$jiekou.uploadBaseUrl + userInfo.head;
				var arr = [];
				var newMessagesOne = newVal[newVal.length - 1];
				// for (var i = 0; i < messageList.length; i++) {
				const isItMe = newMessagesOne.flow == 'out' ? true : false;

				var contentType = 1;
				let content = "";
				var info = null;
				if (newMessagesOne.type == "TIMTextElem") {
					contentType = 1;
					content = newMessagesOne.payload.text;
				} else if (newMessagesOne.type == "TIMImageElem") {
					contentType = 3;
					content = newMessagesOne.payload.imageInfoArray[0].imageUrl;
				} else if (newMessagesOne.type == "TIMSoundElem") {
					contentType = 2;
					content = newMessagesOne.payload.url;
					var contentDuration = newMessagesOne.payload.second;
				} else if (newMessagesOne.type == "TIMCustomElem") {
					contentType = 4;
					content = newMessagesOne.payload.description;
					info = newMessagesOne.payload.extension;
					info = JSON.parse(info);
				}

				arr.push({
					hasBeenSentId: newMessagesOne.ID,
					content,
					fromUserHeadImg: isItMe ? wodeTouxiang : this.meHaed,
					fromUserId: isItMe ? userInfo.id : this.meUserID,
					isItMe,
					createTime: newMessagesOne.time,
					contentType,
					contentDuration,
					info,
					anmitionPlay: false //标识音频是否在播放
				})
				this.messageList = [...this.messageList, ...arr];
				this.$nextTick(function() {
					//进入页面滚动到底部
					uni.pageScrollTo({
						scrollTop: 9999,
						duration: 0
					});
				});
			},
			// 加载初始页面消息
			getMsgList() {
				// 历史消息列表
				// let conversationID = this.conversationActive.conversationID;
				// let promise = this.tim.getMessageList({conversationID: conversationID, count: this.count});
				// promise.then((res)=> {
				// 	this.$store.commit('pushCurrentMessageList',  res.data.messageList)
				//   // this.nextReqMessageID =  res.data.nextReqMessageID // 用于续拉，分页续拉时需传入该字段。11
				//   // this.isCompleted =  res.data.isCompleted
				//   this.scrollToView = res.data.messageList[res.data.messageList.length-1].ID
				// 	console.log(this.nextReqMessageID)
				// 	console.log(this.scrollToView)
				// });
				// 滚动到底部
				// this.$nextTick(function() {
				// 	//进入页面滚动到底部
				// 	this.scrollTop = 9999;
				// 	this.$nextTick(function() {
				// 		this.scrollAnimation = true;
				// 	});
				// });
			},
			//拼接消息 处理滚动
			async joinData() {
				if (!this.loading) {
					//如果没有获取数据 即loading为false时，return 避免用户重复上拉触发加载
					return;
				}
				this.loading = false;
				const data = await this.getMessageData();
				console.log(data);
				// const data = this.getMessageData();
				//获取节点信息
				if(data.length==0){
					this.loading = true;
				}
				const {
					index
				} = this.formData;
				const sel = `#msg-${index > 1 ? this.messageList[0].hasBeenSentId : data[data.length - 1].hasBeenSentId}`;
				this.messageList = [...data, ...this.messageList];
				//填充数据后，视图会自动滚动到最上面一层然后瞬间再跳回bindScroll的指定位置 ---体验不是很好，后期优化
				this.$nextTick(() => {
					this.bindScroll(sel);
					//如果还有数据
					setTimeout(() => {
						this.loading = true;
					}, 200);
					if (this.nextReqMessageID != null) {
						this.formData.index++;
					}
				});
			},
			//处理滚动
			bindScroll(sel, duration = 0) {
				const query = uni.createSelectorQuery().in(this);
				query
					.select(sel)
					.boundingClientRect(data => {
						uni.pageScrollTo({
							// scrollTop: 9999,
							scrollTop: data && data.top - 40,
							duration
						});
					})
					.exec();
			},
			//获取消息
			async getMessageData() {
				var that = this;
				let getData = () => {
					let arr = [];
					var userInfo = uni.getStorageSync("userInfo");
					var wodeTouxiang = that.$jiekou.uploadBaseUrl + userInfo.head;
					var canshu = {
						conversationID: that.conversationActive.conversationID,
						count: that.formData.limit
					};
					if (that.isCompleted) {
						canshu.nextReqMessageID = that.nextReqMessageID;
					}
					console.log(JSON.stringify(canshu));
					let promise = that.tim.getMessageList(canshu);
					promise.then(function(imResponse) {
						const messageList = imResponse.data.messageList; // 消息列表。
						const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段11。
						that.isCompleted = !imResponse.data.isCompleted; // 表示是否已经拉完所有消息
						console.log(imResponse.data.isCompleted);
						console.log(imResponse.data.nextReqMessageID);
						if (!imResponse.data.isCompleted) {
							that.nextReqMessageID = imResponse.data.nextReqMessageID;
						} else {
							that.nextReqMessageID = null;
						}
						console.log(messageList);
						var info = null;
						for (var i = 0; i < messageList.length; i++) {
							const isItMe = messageList[i].flow == 'out' ? true : false;

							var contentType = 1;
							let content = "";
							if (messageList[i].type == "TIMTextElem") {
								contentType = 1;
								content = messageList[i].payload.text;
							} else if (messageList[i].type == "TIMImageElem") {
								contentType = 3;
								content = messageList[i].payload.imageInfoArray[0].imageUrl;
							} else if (messageList[i].type == "TIMSoundElem") {
								contentType = 2;
								content = messageList[i].payload.url;
								var contentDuration = messageList[i].payload.second;
							} else if (messageList[i].type == "TIMCustomElem") {
								contentType = 4;
								content = messageList[i].payload.description;
								info = messageList[i].payload.extension;
								info = JSON.parse(info);
							}

							arr.push({
								hasBeenSentId: messageList[i].ID,
								content,
								fromUserHeadImg: isItMe ? wodeTouxiang : that.meHaed,
								fromUserId: isItMe ? userInfo.id : that.meUserID,
								isItMe,
								info,
								createTime: messageList[i].time,
								contentType,
								contentDuration,
								anmitionPlay: false //标识音频是否在播放
							})
						}
					}).catch(function(err) {
						console.log(JSON.stringify(err));
					});
					return arr;
				};

				return new Promise((resolve, reject) => {
					const data = getData();
					console.log(JSON.stringify(data));
					setTimeout(() => {
						resolve(data);
					}, 500);
				});
				// const data = getData();
				// return data;
			},
			//切换语音或者键盘方式1
			async requestAndroidPermission(permisionID) {
				var result = await permision.requestAndroidPermission(permisionID);
				return result;
			},
			async switchChatType(type) {
				
				var result = await this.requestAndroidPermission('android.permission.RECORD_AUDIO');
				if(result==1){
					this.chatType = type;
					this.showFunBtn = false;
				}else{
					
				}
				// var that = this;
				// console.log(type);
				// if(type=="keyboard"){
				// 	uni.authorize({
				// 	    scope: 'scope.record',
				// 	    success() {
				// 	       that.chatType = type;
				// 	       that.showFunBtn = false;
				// 	    }
				// 	})
				// }else{
				// that.chatType = type;
				// that.showFunBtn = false;
				// }
			},
			//切换功能性按钮
			switchFun() {
				this.chatType = 'keyboard'
				this.showFunBtn = !this.showFunBtn;
				uni.hideKeyboard()
			},
			//发送消息
			sendMsg(data) {

				var that = this;
				const params = {
					hasBeenSentId: Date.now(), //已发送过去消息的id
					content: this.formData.content,
					fromUserHeadImg: this.$jiekou.uploadBaseUrl + this.woUserInfo.head, //用户头像
					fromUserId: this.woUserInfo.id,
					isItMe: true, //true此条信息是我发送的  false别人发送的
					createTime: Date.now(),
					contentType: 1
				};
				if (data) {
					if (data.contentType == 2) {
						//说明是发送语音
						params.content = data.content;
						params.contentType = data.contentType;
						params.contentDuration = data.contentDuration;
						params.anmitionPlay = false;
						console.log("语音对象：" + JSON.stringify(data.audio));
						// 4. 创建消息实例，接口返回的实例可以上屏
						const message = that.tim.createAudioMessage({
							to: that.toUserId + "",
							conversationType: that.$TIM.TYPES.CONV_C2C,
							// 消息优先级，用于群聊（v2.4.2起支持）。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息，详细请参考：https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
							// 支持的枚举值：TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL（默认）, TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
							// priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
							payload: {
								file: data.audio,

							}
						});

						// 5. 发送消息
						let promise = that.tim.sendMessage(message);
						promise.then(function(imResponse) {
							// 发送成功
							console.log(imResponse);
							addMessage(params, message);
						}).catch(function(imError) {
							// 发送失败
							console.warn('sendMessage error:', imError);
						});
					} else if (data.contentType == 3) {
						//发送图片
						params.content = data.content;
						params.contentType = data.contentType;
						// 2. 创建消息实例，接口返回的实例可以上屏
						let message = that.tim.createImageMessage({
							to: that.toUserId + "",
							conversationType: that.$TIM.TYPES.CONV_C2C,
							payload: {
								file: data.pic
							},
							onProgress: function(event) {
								console.log('file uploading:', event)
							}
						});
						// 3. 发送图片
						let promise = that.tim.sendMessage(message);
						promise.then(function(imResponse) {
							// 发送成功
							console.log(imResponse);
							addMessage(params, message);
						}).catch(function(imError) {
							// 发送失败
							console.warn('sendMessage error:', imError);
						});
					} else if (data.contentType == 4) { //发送位置消息
						console.log(data);
						params.info = data.info;
						params.poiName = data.poiName;
						// 2. 创建消息实例，接口返回的实例可以上屏
						let message = that.tim.createCustomMessage({
							to: that.toUserId + "",
							conversationType: that.$TIM.TYPES.CONV_C2C,
							// 消息优先级，用于群聊（v2.4.2起支持）。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息，详细请参考：https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
							// 支持的枚举值：TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL（默认）, TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
							// priority: TIM.TYPES.MSG_PRIORITY_HIGH,
							payload: {
								data: 'weizhi', // 用于标识该消息是骰子类型消息
								description: data.poiName, // 获取骰子点数
								extension: JSON.stringify(data.info)
							}
						});
						// 3. 发送消息
						let promise = that.tim.sendMessage(message);
						promise.then(function(imResponse) {
							// 发送成功
							console.log(imResponse);
							addMessage(params, message);
						}).catch(function(imError) {
							// 发送失败
							console.warn('sendMessage error:', imError);
						});

					}
				} else {
					//验证输入框书否为空字符
					// 发送文本消息，Web 端与小程序端相同
					// 1. 创建消息实例，接口返回的实例可以上屏
					let message = that.tim.createTextMessage({
						to: that.toUserId + "",
						conversationType: that.$TIM.TYPES.CONV_C2C,
						// 消息优先级，用于群聊（v2.4.2起支持）。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息，详细请参考：https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
						// 支持的枚举值：TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL（默认）, TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
						// priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
						payload: {
							text: that.formData.content
						}
					});
					// 2. 发送消息
					let promise = that.tim.sendMessage(message);
					promise.then(function(imResponse) {
						// 发送成功
						console.log(imResponse);
						addMessage(params, message);
					}).catch(function(imError) {
						// 发送失败
						console.warn('sendMessage error:', imError);
						return;
					});

				}

				function addMessage(params, message) {
					that.$store.commit('pushCurrentMessageList', message);

					// that.messageList = [...that.messageList, params];
					that.$nextTick(() => {
						that.formData.content = '';
						// #ifdef MP-WEIXIN
						if (params.contentType == 1) {
							uni.pageScrollTo({
								scrollTop: 99999,
								duration: 0, //小程序如果有滚动效果 input的焦点也会随着页面滚动...
							});
						} else {
							setTimeout(() => {
								uni.pageScrollTo({
									scrollTop: 99999,
									duration: 0, //小程序如果有滚动效果 input的焦点也会随着页面滚动...
								});
							}, 150)
						}
						// #endif

						// #ifndef MP-WEIXIN
						uni.pageScrollTo({
							scrollTop: 99999,
							duration: 100
						});
						// #endif

						if (that.showFunBtn) {
							that.showFunBtn = false;
						}

						// #ifdef MP-WEIXIN 
						if (params.contentType == 1) {
							that.mpInputMargin = true;
						}
						// #endif
						//h5浏览器并没有很好的办法控制键盘一直处于唤起状态 而且会有样式性的问题
						// #ifdef H5
						uni.hideKeyboard();
						// #endif
					});
				}

			},
			//用户触摸屏幕的时候隐藏键盘
			touchstart() {
				uni.hideKeyboard();
			},
			// userid 用户id
			linkToBusinessCard(userId) {
				this.$u.route({
					url: 'pages/businessCard/businessCard',
					params: {
						userId
					}
				});
			},
			//准备开始录音
			startVoice(e) {
				if (!this.Audio.paused) {
					//如果音频正在播放 先暂停。
					this.stopAudio(this.AudioExam)
				}
				this.recording = true;
				this.isStopVoice = false;
				this.canSend = true;
				this.voiceIconText = "正在录音..."
				this.PointY = e.touches[0].clientY;
				this.Recorder.start({
					format: 'mp3'
				});
			},
			//录音已经开始
			beginVoice() {
				if (this.isStopVoice) {
					this.Recorder.stop();
					return;
				}
				this.voiceTitle = '松开 结束'
				this.voiceInterval = setInterval(() => {
					this.voiceTime++;
				}, 1000)
			},
			//move 正在录音中
			moveVoice(e) {
				const PointY = e.touches[0].clientY
				const slideY = this.PointY - PointY;
				if (slideY > uni.upx2px(120)) {
					this.canSend = false;
					this.voiceIconText = '松开手指 取消发送 '
				} else if (slideY > uni.upx2px(60)) {
					this.canSend = true;
					this.voiceIconText = '手指上滑 取消发送 '
				} else {
					this.voiceIconText = '正在录音... '
				}
			},
			//结束录音
			endVoice() {
				this.isStopVoice = true; //加锁 确保已经结束录音并不会录制
				this.Recorder.stop();
				this.voiceTitle = '按住 说话'
			},
			//录音被打断
			cancelVoice(e) {
				this.voiceTime = 0;
				this.voiceTitle = '按住 说话';
				this.canSend = false;
				this.Recorder.stop();
			},
			//处理录音文件
			handleRecorder(res) {
				let contentDuration;
				// #ifdef MP-WEIXIN
				this.voiceTime = 0;
				if (res.duration < 600) {
					this.voiceIconText = "说话时间过短";
					setTimeout(() => {
						this.recording = false;
					}, 200)
					return;
				}
				contentDuration = res.duration / 1000;
				// #endif

				// #ifdef APP-PLUS
				contentDuration = this.voiceTime + 1;
				this.voiceTime = 0;
				if (contentDuration <= 0) {
					this.voiceIconText = "说话时间过短";
					setTimeout(() => {
						this.recording = false;
					}, 200)
					return;
				};
				// #endif


				this.recording = false;
				res.duration = contentDuration * 1000;
				console.log(res);
				const params = {
					contentType: 2,

					content: res.tempFilePath,
					contentDuration: Math.ceil(contentDuration),
					audio: res
				};
				this.canSend && this.sendMsg(params);
			},
			//控制播放还是暂停音频文件
			handleAudio(item) {
				this.AudioExam = item;
				this.Audio.paused ? this.playAudio(item) : this.stopAudio(item);
			},
			//播放音频
			playAudio(item) {
				this.Audio.src = item.content;
				this.Audio.hasBeenSentId = item.hasBeenSentId;
				this.Audio.play();
				item.anmitionPlay = true;
			},
			//停止音频
			stopAudio(item) {
				item.anmitionPlay = false;
				this.Audio.src = '';
				this.Audio.stop();
			},
			//关闭动画
			closeAnmition() {
				const hasBeenSentId = this.Audio.hasBeenSentId;
				const item = this.messageList.find(it => it.hasBeenSentId == hasBeenSentId);
				item.anmitionPlay = false;
			},
			//点击宫格时触发
			clickGrid(index) {
				var that = this;
				if (index == 0) {
					this.chooseImage(['album'])
				} else if (index == 1) {
					this.chooseImage(['camera'])
				} else if (index == 2) { //位置

					uni.getLocation({
						type: 'gcj02',
						geocode: true,
						success: function(res) {
							console.log('当前位置的经度：' + res.longitude);
							console.log('当前位置的纬度：' + res.latitude);
							console.log(JSON.stringify(res.address));
							var address = "";
							if (res.address.country != undefined) {
								address += res.address.country;
							}
							if (res.address.province != undefined) {
								address += res.address.province;
							}
							if (res.address.city != undefined) {
								address += res.address.city;
							}
							if (res.address.district != undefined) {
								address += res.address.district;
							}
							if (res.address.street != undefined) {
								address += res.address.street;
							}
							if (res.address.streetNum != undefined) {
								address += res.address.streetNum;
							}
							var poiName = "";
							if (res.address.poiName != undefined) {
								poiName += res.address.poiName;
							}
							const params = {
								contentType: 4,
								poiName: poiName,
								info: {
									longitude: res.longitude,
									latitude: res.latitude,
									address: address
								}
							};
							that.showFunBtn = false;
							that.sendMsg(params);
						}
					});
					// uni.chooseLocation({
					// 	success: (res) => {
					// 		console.log(JSON.stringify(res));
					// 		this.hasLocation = true,
					// 			this.location = formatLocation(res.longitude, res.latitude),
					// 			this.locationAddress = res.address;
					// 			console.log(JSON.stringify(this.amapPlugin));
					// 			this.amapPlugin.getRegeo({
					// 				location:res.longitude+","+res.latitude,
					// 				success:function(data){
					// 					console.log(JSON.stringify(data));
					// 				}
					// 			})

					// 	}
					// })
				}
			},
			//发送图片
			chooseImage(sourceType) {
				uni.chooseImage({
					count: 1,
					sourceType,
					sizeType: ['compressed'],
					success: res => {
						this.showFunBtn = false;
						for (let i = 0; i < res.tempFilePaths.length; i++) {
							const params = {
								contentType: 3,
								content: res.tempFilePaths[i],
								pic: res
							};
							this.sendMsg(params)
						}
					}
				})
			},
			//查看大图
			viewImg(imgList) {
				uni.previewImage({
					urls: imgList,
					// #ifndef MP-WEIXIN
					indicator: 'number'
					// #endif
				});
			},
		},
		onPageScroll(e) {
			if (e.scrollTop < 50 && this.isCompleted) {
				this.joinData();
			}
		},
		onNavigationBarButtonTap({
			index
		}) {
			if (index == 0) {
				//用户详情 设置
			} else if (index == 1) {
				//返回按钮
				this.$u.route({
					type: 'switchTab',
					url: 'pages/home/home'
				});
			}
		},
		//返回按钮事件
		onBackPress(e) {
			//以下内容对h5不生效1
			//--所以如果用浏览器自带的返回按钮进行返回的时候页面不会重定向 正在寻找合适的解决方案
			// this.$u.route({
			// 	type: 'switchTab',
			// 	url: 'pages/home/home'
			// });
			// return true;
			// uni.switchTab({
			//     url: 'pages/home/home'
			// });
			// uni.navigateBack();
		},
		onLoad(info) {
			// this.requestAndroidPermission('android.permission.RECORD_AUDIO');
			
			
			this.meHaed = uni.getStorageSync("meHead");;
			this.getMsgList();
			this.amapPlugin = new amap.AMapWX({
				key: this.key
			});


			//录音开始事件
			this.Recorder.onStart(e => {

				this.beginVoice();
			});
			//录音结束事件
			this.Recorder.onStop(res => {
				clearInterval(this.voiceInterval);
				console.log(res);
				var that = this;
				uni.getFileInfo({
					"filePath": res.tempFilePath,
					success(data) {
						res.fileSize = data.size;
						that.handleRecorder(res);
					}
				})

			});

			//音频停止事件
			this.Audio.onStop(e => {
				this.closeAnmition();
			});

			//音频播放结束事件
			this.Audio.onEnded(e => {
				this.closeAnmition();
			});
		},
		onReady() {
			//自定义返回按钮 因为原生的返回按钮不可阻止默认事件
			// #ifdef H5
			const icon = document.getElementsByClassName('uni-page-head-btn')[0];
			icon.style.display = 'none';
			// #endif

			uni.setNavigationBarTitle({
				title: this.fromUserInfo.fromUserName
			});
			this.joinData();
			uni.getSystemInfo({
				success: res => {
					this.imgHeight = res.windowHeight + 'px';
				}
			});

			uni.onKeyboardHeightChange(res => {
				if (res.height == 0) {
					// #ifdef MP-WEIXIN
					this.mpInputMargin = false;
					// #endif
				} else {
					this.showFunBtn = false;
				}
			});
		}
	};
</script>

<style lang="scss" scoped>
	// @import '@/static/iconfont/iconfont.css'	;
	@import './index.scss'
</style>
